<template>
  <client-only>
    <div class="header-container">
      <div class="wrapper">
        <!-- logo -->
        <div class="left-wrapper v-link selected">
          <img style="width: 50px" width="50" height="50" src="~assets/images/logo.jpeg" />
          <el-link :underline="false" type="primary" href="/"><span class="text">
              预约挂号统一平台
            </span></el-link>

        </div>
        <!-- 搜索框 -->
        <div class="search-wrapper">
          <div class="hospital-search animation-show">
            <el-autocomplete class="search-input small" prefix-icon="el-icon-search" v-model="hosname"
              :fetch-suggestions="querySearchAsync" placeholder="点击输入医院名称" @select="handleSelect1">
              <span slot="suffix" class="search-btn v-link highlight clickable selected">搜索
              </span>
            </el-autocomplete>
          </div>
        </div>
        <!-- 右侧 -->
        <div class="right-wrapper">
          <span class="v-link clickable">帮助中心</span>
          <span v-if="name == ''" class="v-link clickable" @click="showLogin()" id="loginDialog">登录/注册</span>
          <el-dropdown v-if="name != ''" @command="loginMenu">
            <span class="el-dropdown-link">
              {{name}}
              <i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu class="user-name-wrapper" slot="dropdown">
              <el-dropdown-item command="/user">实名认证</el-dropdown-item>
              <el-dropdown-item command="/order">挂号订单</el-dropdown-item>
              <el-dropdown-item command="/patient">就诊人管理</el-dropdown-item>
              <el-dropdown-item command="/logout" divided>退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>

      </div>

      <!-- 登录弹出层 -->

      <el-dialog v-if="dialogUserFormVisible" :visible.sync="dialogUserFormVisible" style="text-align: left;" top="50px"
        :append-to-body="true" width="960px" @close="closeDialog()">
        <div class="container">

          <div class="operate-view" v-if="dialogAtribute.showLoginType === 'phone'">
            <div class="wrapper" style="width: 100%">
              <div class="mobile-wrapper" style="position: static;width: 70%">
                <span class="title">{{ dialogAtribute.labelTips }}</span>
                <el-form>
                  <el-form-item>
                    <el-input v-model="dialogAtribute.inputValue" :placeholder="dialogAtribute.placeholder"
                      :maxlength="dialogAtribute.maxlength" class="input v-input">
                      <span slot="suffix" class="sendText v-link"
                        v-if="dialogAtribute.second > 0">{{ dialogAtribute.second }}s
                      </span>
                      <span slot="suffix" class="sendText v-link highlight clickable selected"
                        v-if="dialogAtribute.second == 0" @click="getCodeFun()">重新发送
                      </span>
                    </el-input>
                  </el-form-item>
                </el-form>
                <div class="send-button v-button" @click="btnClick()">
                  {{ dialogAtribute.loginBtn }}
                </div>
              </div>
              <div class="bottom">
                <div class="wechat-wrapper" @click="weixinLogin()">
                  <span class="iconfont icon"></span>
                </div>
                <span class="third-text"> 第三方账号登录 </span>
              </div>
            </div>
          </div>

          <div class="operate-view" v-if="dialogAtribute.showLoginType === 'weixin'">
            <div class="wrapper wechat" style="height: 400px">
              <div>
                <div id="weixinLogin"></div>
              </div>
              <div class="bottom wechat" style="margin-top: -80px;">
                <div class="phone-container">
                  <div class="phone-wrapper" @click="phoneLogin()">
                    <span class="iconfont icon"></span>
                  </div>
                  <span class="third-text"> 手机短信验证码登录 </span>
                </div>
              </div>
            </div>
          </div>

          <div class="info-wrapper">
            <div class="code-wrapper">
              <div>
                <img src="~assets/images/54db2b3e968cebc19676761bbe712b5.jpg" class="code-img" />
                <div class="code-text">
                  <span class="iconfont icon"></span>微信扫一扫关注
                </div>
                <div class="code-text">快速关注</div>
              </div>
              <div class="wechat-code-wrapper">
                <img src="~assets/images/c506b1dba0599df6c7fce383d840e63.jpg" class="code-img" />
                <div class="code-text"><span class="iconfont icon"></span>扫一扫加好友</div>
                <div class="code-text">哈哈</div>
              </div>
            </div>
            <div class="slogan">
              <div>xxxxxx官方指定平台</div>
              <div>快速关注 安全放心</div>
            </div>
          </div>
        </div>
      </el-dialog>

    </div>
  </client-only>
</template>

<script>
import cookie from 'js-cookie'
import Vue from 'vue'

export default {
  data () {
    return {
      //
      hosname: '',
      name: '',
      // 对话框的打开变量
      dialogUserFormVisible: false,
      // 对话框属性
      dialogAtribute: {
        showLoginType: 'phone', // 控制手机登录与微信登录切换
        labelTips: '手机号码', // 输入框提示
        inputValue: '', // 输入框绑定对象
        placeholder: '请输入您的手机号', // 输入框placeholder
        maxlength: 11, // 输入框长度控制
        loginBtn: '获取验证码', // 登录按钮或获取验证码按钮文本
        sending: true,      // 是否可以发送验证码
        second: -1,        // 倒计时间  second>0 : 显示倒计时 second=0 ：重新发送 second=-1 ：什么都不显示
        clearSmsTime: null  // 倒计时定时任务引用 关闭登录层清除定时任务
      },
      // 登录的对象
      userInfo: {
        phone: '',
        code: '',
        openid: ''
      },
    }
  },
  methods: {
    // 搜索框建议方法
    querySearchAsync (queryString, cb) {
      let arr = new Array()
      if (this.hosname != '') {
        this.$axios.get(`/admin/hosp/nuxtHospital/findHospitalByHosname/${this.hosname}`).then(({ data }) => {
          data.data.forEach(e => {
            let allInfos = {
              hoscode: e.hoscode,
              value: e.hosname
            }
            arr.push(allInfos)
          })
        })
      }
      cb(arr)
    },
    // 选择搜索框建议的方法
    handleSelect1 (item) {
      // 点击进入详情页面
      // 取到hoscode进行跳转查询
      window.location.href = '/hosp/' + item.hoscode
    },
    // 点击登录注册的方法
    showLogin () {
      this.dialogUserFormVisible = true
    },
    // 下拉菜单指令事件
    loginMenu (command) {
      if ('/logout' == command) {
        cookie.set("token", '', { domain: 'localhost' })
        cookie.set("name", '', { domain: 'localhost' })
        // 跳转页面
        window.location.href = '/'
      } else {
        window.location.href = command
      }
    },
    // 关闭对话框的方法
    closeDialog () {
      this.dialogUserFormVisible = false
    },
    // 获取验证码和登录一个按钮
    btnClick () {
      // 获取验证码操作
      if (this.dialogAtribute.sending && this.dialogAtribute.loginBtn === '获取验证码') {
        this.dialogAtribute.loginBtn = '正在发送...'
        this.$axios.get(`https://cloud-music-api-lyart.vercel.app/captcha/sent?phone=${this.dialogAtribute.inputValue}`).then(result => {
          if (result.data.data) {
            this.$axios.get(`/api/sms/receivePhone/${this.dialogAtribute.inputValue}`).then(({ data }) => { })
            this.$message({
              message: '验证码发送成功！',
              type: 'success'
            })
            this.userInfo.phone = this.dialogAtribute.inputValue
            this.dialogAtribute.inputValue = ''
            this.dialogAtribute.placeholder = '请输入验证码'
            this.dialogAtribute.loginBtn = '马上登录'
            this.dialogAtribute.second = 60
            this.dialogAtribute.sending = false
            this.dialogAtribute.maxlength = 4
            this.dialogAtribute.clearSmsTime = setInterval(() => {
              this.dialogAtribute.second = this.dialogAtribute.second - 1
              if (this.dialogAtribute.second < 1) {
                clearInterval(this.dialogAtribute.clearSmsTime)
              }
            }, 1000)
          } else {
            this.dialogAtribute.loginBtn = '获取验证码'
            this.$message.error('发送失败！请稍后再试')
          }
        }).catch(e => {
          this.dialogAtribute.loginBtn = '获取验证码'
          this.$message.error('发送失败！请稍后再试')
        })
      } else {
        // 登录操作
        if (this.dialogAtribute.loginBtn === '正在发送...') {
          this.$message({
            type: 'warning',
            message: '请稍后再获取'
          })
        } else {
          this.userInfo.code = this.dialogAtribute.inputValue
          if (this.userInfo.code === '' || this.userInfo.code.length != 4) {
            this.$message({
              type: 'error',
              message: '请输入有效验证码'
            })
          } else {
            const loading = this.$loading({
              lock: true,
              text: '正在登录...',
              spinner: 'el-icon-loading',
              background: 'rgba(180, 209, 238, 0.7)'
            })
            this.$axios.post(`/api/user/userInfo/login`, this.userInfo).then(({ data }) => {
              this.userInfo.code = this.dialogAtribute.inputValue
              if (data.code == 200) {
                this.$axios.get(`https://cloud-music-api-lyart.vercel.app/captcha/verify?phone=${this.userInfo.phone}&captcha=${this.userInfo.code}`).then(result => {
                  if (result.data.data) {
                    this.$axios.post(`/api/user/userInfo/successLogin/${this.userInfo.phone}`).then(({ data }) => {
                      loading.close()
                      this.$message({
                        message: '登录成功',
                        type: 'success'
                      })
                      this.setCookie(data.data.name, data.data.token)
                    }).catch(e => {
                      loading.close()
                    })
                  } else {
                    loading.close()
                    this.$message.error('验证码错误')
                  }
                }).catch((er) => {
                  loading.close()
                  this.$message.error('验证失败')
                })
              } else {
                if (data.data == 'status') {
                  this.$message.error("账号已被锁定，无法登陆，请更换账号登录")
                } else {
                  this.$message.error("验证码已过期，请重新获取")
                }
                loading.close()
              }
            }).catch(e => {
              loading.close()
            })
          }
        }
      }

    },
    // 重新获取验证码
    getCodeFun () {
      this.$axios.get(`https://cloud-music-api-lyart.vercel.app/captcha/sent?phone=${this.dialogAtribute.inputValue}`).then(result => {
        if (result.data.data) {
          this.$axios.get(`/api/sms/receivePhone/${this.dialogAtribute.inputValue}`).then(({ data }) => { })
          this.$message({
            message: '验证码发送成功！',
            type: 'success'
          })
          this.dialogAtribute.placeholder = '请输入验证码'
          this.dialogAtribute.second = 60
          this.dialogAtribute.clearSmsTime = setInterval(() => {
            this.dialogAtribute.second = this.dialogAtribute.second - 1
            if (this.dialogAtribute.second < 0) {
              clearInterval(this.dialogAtribute.clearSmsTime)
            }
          }, 1000)
        } else {
          this.$message.error('发送失败！请稍后再试')
        }
      }).catch(e => {
        this.$message.error('发送失败！请稍后再试')
      })
    },
    // 微信登录
    weixinLogin () {
      this.dialogAtribute.showLoginType = 'weixin'

      //初始化微信相关参数
      this.$axios.get(`/api/ucenter/wx/getLoginParam`).then(response => {
        var obj = new WxLogin({
          self_redirect: true,
          id: 'weixinLogin', // 需要显示的容器id
          appid: response.data.appid, // 公众号appid wx*******
          scope: response.data.scope, // 网页默认即可
          redirect_uri: response.data.redirect_uri, // 授权成功后回调的url
          state: response.data.state, // 可设置为简单的随机数加session用来校验
          style: 'black', // 提供"black"、"white"可选。二维码的样式
          href: '' // 外部css文件url，需要https
        })

      })
    },
    // 手机号登录
    phoneLogin () {
      this.dialogAtribute.showLoginType = 'phone'
      this.showLogin()
    },
    // 设置cookie的方法
    setCookie (name, token) {
      cookie.set("token", token, { domain: 'localhost' })
      cookie.set("name", name, { domain: 'localhost' })
      window.location.reload()
    },
    // 显示用户信息的方法
    showUserInfo () {
      let token = cookie.get('token')
      if (token) {
        let name = cookie.get('name')
        this.name = name
      }
    },
    //微信登录
    loginCallback (name, token, openid) {
      // 打开手机登录层，绑定手机号，改逻辑与手机登录一致
      this.userInfo.openid = openid
      this.setCookie(name, token)
    },
  },
  // 加载事件
  created () {
    this.showUserInfo()
  },
  // 页面渲染之后执行的方法
  mounted () {
    // 注册全局登录事件对象
    window.loginEvent = new Vue()
    // 监听登录事件
    loginEvent.$on('loginDialogEvent', function () {
      document.getElementById('loginDialog').click()
    })

    //初始化微信js
    const script = document.createElement('script')
    script.type = 'text/javascript'
    script.src = 'https://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js'
    document.body.appendChild(script)

    //微信回调的方法
    let self = this;
    window["loginCallback"] = (name, token, openid) => {
      self.loginCallback(name, token, openid);
    }
  }
}
</script>

